import React, { useRef, useState } from "react";
import { Button, Space, message } from "antd";
import { useRequest } from "ahooks";
import { PlusOutlined } from '@ant-design/icons';
import { ProColumnType, ProTable } from "@ant-design/pro-components";
import { lineTypes, modalPropsType, lineBatchTypes  } from "@/constants/types";
import { fetchLpsLineList, addLpsLine, updateLpsLine, addLpsLineBatch } from "../services";
import LpsLineUpdateModal from "../modals/LpsLineUpdate";
import LineBatchUpdate from "../modals/LineBatchUpdate";
import { useModel } from "@umijs/max";
import { fetchServiceProviderOptions } from "@/pages/BasicInfo/services";

const LineList = () => {
  const tableRef = useRef();
  // line
  const [visible, setVisible] = useState<boolean>(false);
  const [currentRow, setCurrentRow] = useState<lineTypes | null>(null);
  const {loading: addLoading, runAsync: addApi} = useRequest(addLpsLine, {manual: true});
  const {loading: updateLoading, runAsync: updateApi} = useRequest(updateLpsLine, {manual: true});
  // lineBatch
  const [lineBatchVisible, setLineBatchVisible] = useState<boolean>(false);
  const {loading: addLineBatchLoading, runAsync: addLineBatchApi} = useRequest(addLpsLineBatch, {manual: true});

  // dict
  const {getDict} = useModel('dictModel');
  const countrys = getDict('country');
  const prdList = getDict('prdType');
  const sportList = getDict('sport');
  const dportList = getDict('dport');


  const lpsLineUpdateProps: modalPropsType = {
    title: currentRow ? '修改线路' : '新建线路',
    visible,
    currentRow,
    loading: addLoading || updateLoading,
    onCancel: () => {
      setVisible(false);
      setCurrentRow(null);
    },
    onSubmit: async (params: lineTypes) => {
      const apiFunc = currentRow ? updateApi : addApi;
      const res = await apiFunc(currentRow ? {
        ...params, 
        id: currentRow?.id
      } : params);
      if (res.code === '0') {
        message.success('操作成功');
        setVisible(false);
        setCurrentRow(null);
        tableRef?.current?.reload();
      }
    }
  }

  const lineBatchProps: modalPropsType = {
    title: '添加船期',
    visible: lineBatchVisible,
    lineRow: currentRow,
    loading: addLineBatchLoading,
    onCancel: () => {
      setLineBatchVisible(false);
      setCurrentRow(null);
    },
    onSubmit: async (params: lineBatchTypes) => {
      const res = await addLineBatchApi(currentRow ? {
        ...params, 
        id: currentRow?.id
      } : params);
      if (res.code === '0') {
        message.success('操作成功');
        setLineBatchVisible(false);
        setCurrentRow(null);
      }
    }
  }
  const handleAdd = () => {
    setCurrentRow(null);
    setVisible(true);
  }
  const handleLineBatchAdd = (record: lineTypes) => {
    setCurrentRow(record);
    setLineBatchVisible(true);
  }
  const handleEdit = (record: lineTypes) => {
    setCurrentRow(record);
    setVisible(true);
  }

  const columns: ProColumnType<lineTypes> [] = [
    {
      title: '国家',
      dataIndex: 'country',
      hideInTable: true,
      valueType: 'select',
      fieldProps: {
        options: countrys
      }
    },
    {
      title: '起始地',
      dataIndex: 'sportCode',
      hideInTable: true,
      valueType: 'select',
      fieldProps: {
        options: sportList
      }
    },
    {
      title: '目的港',
      dataIndex: 'dportCode',
      hideInTable: true,
      valueType: 'select',
      fieldProps: {
        options: dportList
      }
    },
    {
      title: '船司',
      dataIndex: 'shipCode',
      hideInTable: true,
      request: async () => {
        const res = await fetchServiceProviderOptions({type: 'ship'});
        return (res || []).map((v: {name: string, code: string}) => ({label: v?.name, value: v?.code}));
      }
    },
    {
      title: '产品',
      dataIndex: 'product',
      hideInTable: true,
      valueType: 'select',
      fieldProps: {
        options: prdList
      }
    },
    {
      title: '线路名称',
      width: 200,
      dataIndex: 'name',
      search: false,
    },
    {
      title: '国家',
      width: 120,
      dataIndex: 'countryName',
      search: false,
    },
    {
      title: '产品名称',
      width: 120,
      dataIndex: 'productName',
      search: false
    },
    {
      title: '起始地',
      width: 120,
      dataIndex: 'sportName',
      search: false
    },
    {
      title: '目的港',
      width: 120,
      dataIndex: 'dportName',
      search: false
    },
    {
      title: '船司',
      dataIndex: 'shipNames',
      ellipsis: true,
      search: false,
    },
    {
      title: '收货仓库',
      dataIndex: 'cwhNames',
      search: false,
      ellipsis: true,
    },
    {
      title: '操作',
      dataIndex: 'options',
      width: 180,
      fixed: 'right',
      search: false,
      render: (_, record: lineTypes) => {
        return (
          <Space>
            <Button type="link" onClick={() => handleEdit(record)}>编辑</Button>
            <Button type="link" onClick={() => handleLineBatchAdd(record)}>添加船期</Button>
          </Space>
        );
      }
    }
  ];

  return (
    <> 
      <ProTable
        bordered
        actionRef={tableRef}
        options={false}
        columns={columns}
        search={{span: 4}}
        scroll={{y: 590}}
        toolBarRender={() => [
          <Button onClick={handleAdd} type="primary">
            <PlusOutlined />
            创建线路
          </Button>,
        ]}
        request={async (params = {}, sort, filter) => {
          console.log(sort, filter);
          params.pageNum = params.current;
          const res = await fetchLpsLineList({
            ...params,
            pageNum: params.current || 1,
            pageSize: params.pageSize || 20,
          });
          return {
            data: res.data || [],
            total: res.total || 0,
            success: true
          }
        }}
      />
      {visible && <LpsLineUpdateModal {...lpsLineUpdateProps} />}
      {lineBatchVisible && <LineBatchUpdate {...lineBatchProps} />}
    </>
  );
};


export default LineList;